package com.mate.cloud.order.handler;

import com.mate.cloud.order.domain.OrderDTO;
import com.mate.cloud.core.response.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 订单处理责任链
 * 封装组合责任链
 * 通过@Autowired修饰责任链（处理器的集合），spring容器会按照@order的顺序组装一个有序的list集合。
 * 通过@PostConstruct修饰constructChain()方法，使容器回调此方法，完成为每一个处理设置它的下一个处理器
 * 定义firstHandler,表示这是当前责任链路顶端的第一个处理器。
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2025/1/27 15:01
 * @updateUser: MI
 * @updateTime: 2025/1/27 15:01
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Service
public class OrderChainHandler {

    @Autowired
    private List<AbstractOrderChainHandler> chain;

    private AbstractOrderChainHandler firstHandler;


    @PostConstruct
    private void constructChain() {
        if (chain == null || chain.size() == 0) {
            throw new RuntimeException("not found order chain handler");
        }
        firstHandler = chain.get(0);
        for (int i = 0; i < chain.size(); i++) {
            if (i == chain.size() - 1) {
                chain.get(i).setNextHandler(null);
            } else {
                chain.get(i).setNextHandler(chain.get(i + 1));
            }
        }
    }

    public BaseResponse executionChain(OrderDTO orderDTO) {
        return firstHandler.doFilter(orderDTO);
    }

}
